package com.zdc.learn.netty.proto;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.Random;

public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("############################");
        int random = new Random().nextInt(3);
        ProtoTest.Mymessage mymessage = null;
        System.out.println("random："+random);
        if (random == 0){
            mymessage = ProtoTest.Mymessage.newBuilder().setDataType(ProtoTest.Mymessage.DataType.StudentType).setStudent(
                    ProtoTest.Student.newBuilder().setId(1).setName("涨势").build()
            ).build();
        }else{
            mymessage = ProtoTest.Mymessage.newBuilder().setDataType(ProtoTest.Mymessage.DataType.WorkerType).setWorker(
                    ProtoTest.Worker.newBuilder().setAge(17).setName("李四").build()
            ).build();
        }
        ctx.channel().writeAndFlush(mymessage);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuffer = (ByteBuf)msg;
        System.out.println("获取服务端过来的数据。。。。。。。。。。。:"+byteBuffer.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        String msg = "客户端收到,已处理完成。。";
        System.out.println(msg);
        //ctx.writeAndFlush(Unpooled.copiedBuffer(msg,CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
       System.out.println("客户端异常："+cause);
    }
}
